using System.IO;
using System.Text;
using System.Text.Json;
using OracleInternal.Json.Binary;
using OracleInternal.Json.Sql;
using OracleInternal.TTC.Accessors;

namespace OracleInternal.ServiceObjects
{
	internal class OracleJsonImpl
	{
		internal const int JSON_MAX_SIZE = 33554432;

		internal const int JSON_DEFAULT_PREFETCH_SIZE = 33554432;

		internal const int JSON_AVG_Size = 0;

		internal static string GetJsonString(int currentRow, int columnIndex, OracleConnectionImpl connImpl, byte[] lobLocator, DataUnmarshaller dataUnmarshaller, TTCJsonAccessor jsonAccessor, ref OracleBlobImpl oraBlobImpl)
		{
			return Decode(OracleBlobImpl.GetCompleteBlobData(currentRow, columnIndex, connImpl, lobLocator, dataUnmarshaller, jsonAccessor, ref oraBlobImpl));
		}

		internal static string Decode(byte[] oson)
		{
			OsonContext osonContext = new OsonContext(new OsonBuffer(new MemoryStream(oson)));
			OracleJsonValue value = (OracleJsonValue)OsonStructure.GetValueInternal(osonContext.GetHeader().GetTreeSegmentOffset(), osonContext.GetFactory(), osonContext);
			StringWriter stringWriter = new StringWriter();
			OracleJsonSerializer oracleJsonSerializer = new OracleJsonSerializer(stringWriter);
			oracleJsonSerializer.Write(value);
			oracleJsonSerializer.Close();
			stringWriter.Close();
			return stringWriter.ToString();
		}

		internal static byte[] Encode(string jsonStr)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(jsonStr);
			Utf8JsonReader parser = new Utf8JsonReader(bytes);
			OracleJsonFactory oracleJsonFactory = new OracleJsonFactory();
			MemoryStream memoryStream = new MemoryStream();
			OracleJsonGenerator oracleJsonGenerator = oracleJsonFactory.createJsonBinaryGenerator(memoryStream);
			oracleJsonGenerator.WriteParser(parser);
			oracleJsonGenerator.Close();
			return memoryStream.ToArray();
		}
	}
}
